/**************************************************************************
 * 新书分发中的方法
 ************************************************************************/

// 新书分发中的选择客户按钮
function chooseClient(obj){
	// 获取界面上预分发数，如果预分发数没有填写不能点开选择客户界面
	var yffs = $('#ffc_addWinForm input[qucln = YFF_AMOUNT]').val();
	if(yffs != null && yffs != '' ){
		_data_qw('cff','ds_client_for_ff','cab_sure1','44','',''); 
	}else{
		$.messager.alert('提示','亲,预分发数没有填写哦！');
		return;
	}
}
// 新书分发中选择客户中的确定按钮
function _cab_sure(){
	$('#cff_DATA_PARENT_PANEL').window('close');
	var selRows = $('#cff_DATA_DATALIST').datagrid('getSelections');
	var allRows = $('#ffc_addItemDatagrid').datagrid('getRows');
	var yffs = $('#ffc_addWinForm input[qucln = YFF_AMOUNT]').val(); //首印数
	var length=allRows.length;
	var jhs = 0;
	var clId = '';
	var address = "";
	var sortNum = getSortNum('ffc');	
	if(length==0){
		for ( var i = 0; i < selRows.length; i++) {
			if(selRows[i].RATIO == '' || selRows[i].RATIO == null){
				selRows[i].RATIO = 0;
			}
			jhs =  parseFloat(selRows[i].RATIO*yffs);
			jhs = jhs.toFixed(0); 
			clId = selRows[i].CLIENTS_ID;
			address = getAdressByClient(clId);
			$('#ffc_addItemDatagrid').datagrid('appendRow', {
				CC_ID: selRows[i].CC_ID,
				C_ID:selRows[i].CLIENTS_ID,
				O_ID_LASTGR:selRows[i].O_ID_LASTGR,
				RATIO:selRows[i].RATIO,				//客户占比年份，隐藏项
				RATIO_YEAR:selRows[i].RATIO_YEAR,	//年份
				TM_ITEM_ID:selRows[i].TM_ITEM_ID,	//模板明细外键，隐藏项
				PLAN_AMOUNT:jhs,
				C_ADDRESS_SEND:address,
				SORT_NUM:parseInt(sortNum)*10+10+parseInt(i)*10
			});
		}
	}else{
		for ( var j = 0; j < selRows.length; j++) {
			currRow=selRows[j];
			if(currRow.RATIO == '' || currRow.RATIO == null){
				currRow.RATIO = 0;
			}
			jhs = parseFloat((currRow.RATIO)*yffs);
			jhs = jhs.toFixed(0); 
			for(var i=0;i<allRows.length;i++){
				if(currRow.CLIENTS_ID==allRows[i].C_ID){
					break;
				}else{
					if(i==(allRows.length-1)){
						clId = currRow.CLIENTS_ID;
						address = getAdressByClient(clId);
						$('#ffc_addItemDatagrid').datagrid('appendRow', {
							CC_ID: currRow.CC_ID,
							C_ID:currRow.CLIENTS_ID,
							O_ID_LASTGR:currRow.O_ID_LASTGR,
							PLAN_AMOUNT:jhs,
							C_ADDRESS_SEND:address,
							RATIO:currRow.RATIO,			//客户占比年份，隐藏项
							TM_ITEM_ID:currRow.TM_ITEM_ID,	//模板明细外键，隐藏项
							SORT_NUM:parseInt(sortNum)*10+10+parseInt(j)*10
						});
					}
				}
			}
		}
	}
}
// 新书分发 中自动数量的按钮(暂时不使用)
function zdAmount(obj){
	var allRows = $('#ffc_addItemDatagrid').datagrid('getRows');
	if(allRows.length==0){
		$.messager.show({title:"操作提示",msg:"亲，明细表中没有数据哦！",showType:'slide',timeout: 2000,showSpeed:400});
		return;
	}else{
		for(var i = 0;i<allRows.length;i++){
			$('#ffc_addItemDatagrid').datagrid('endEdit',i);
			allRows[i].SEND_AMOUNT = allRows[i].PLAN_AMOUNT;
			$('#ffc_addItemDatagrid').datagrid('beginEdit',i);
			$('#ffc_addItemDatagrid').datagrid('endEdit',i);
		}
	}
}

//全局变量
//var isort = 1;
// 新书分发中追加地址的按钮
function fzkhFunc(obj){
	var dsId = 'ds_fx_ff_clients2;ds_fx_ff_clients_item2';
	$('#ffc_addItemDatagrid').datagrid("endAllEdit");
	var selRows = $('#ffc_addItemDatagrid').datagrid('getSelections');
	var currentIndex=$('#ffc_addItemDatagrid').datagrid("getRowIndex",selRows[0]);
	var insertRow={};
	if(selRows.length == 0){
		$.messager.alert('提示','亲，你没有选中任何一条数据哦！');
		return;
	}else if(selRows.length >1){
		$.messager.alert('提示','亲，只能选中一行数据进行复制哦！');
		return;
	}else{
		for(p in selRows[0]){
			insertRow[p]=selRows[0][p];
		}
		insertRow["C_ADDRESS_SEND"]="";    
		insertRow["FFC_ITEM_ID"]="";     
		$('#ffc_addItemDatagrid').datagrid('insertRow',{index:(parseInt(currentIndex)+1),row:insertRow});
		sjAmount_cal("ffc_addItemDatagrid")
	}
}
//判断客户和地址重复的方法  editor中,func:'khffAddress'
//暂时不进行使用，可以进行一个地址的多个选择 
function khffAddress(value,prefix){
	//判断明细数据中是否存在一个客户一个地址的多行数据，如果有则不能保存，如果没有，则可以保存成功
	var cindex = $('#'+prefix+'_addItemDatagrid').attr('currentindex'); 			//获取选中行的下标
	var allRows = $('#'+prefix+'_addItemDatagrid').datagrid('getRows'); 			//明细表中所有的数据
	var selRow = allRows[cindex]; 													//选中行数据
	var cId = selRow.C_ID;															//获取客户的id
	for(var i = 0;i<allRows.length;i++){
		if(i != cindex){
			if(allRows[i].C_ID == cId){
				if(allRows[i].C_ADDRESS_SEND == value){
					$($($('#'+prefix+'_addItemDatagrid').datagrid("getEditor",{index:cindex,field:'C_ADDRESS_SEND'}).target[0]).parent("td").find("select")[0]).val("");
					$.messager.alert('温馨提示','亲，该客户的这个地址已经被选择过了！请重新选择');
					return;
				}
			}
		}
	}
}

//新手分发选择商品选择调用的方法
function getStockAmountHID(obj){
	var hId = $(obj).val();
	stockAmount(hId,'0');
}
//库房选择调用的方法
function getStockAmountSID(obj){
	var sId = $(obj).val();
	stockAmount(sId,'1');
}

//根据商品Id和库房Id获取有效库存
function stockAmount(objVal,flag){
	var hId = "";
	var sId = "";
	if(flag == '0'){ //商品
		hId= objVal;
		sId = $('#ffc_addWinForm select[qucln = STOCK_ID]').val(); //库房
	}else if(flag == '1'){ //库房
		hId = $('#ffc_addWinForm input[qucln = H_ID]').val(); //商品Id
		sId= objVal;
	}
	var keyVal = new Array();
	keyVal.push(hId);
	keyVal.push(sId);
	if(hId != null && sId != null){
		$.ajax({
			type:'post',
			url:_m_url+'fxa/getStockNumByHidStock',
			contentType: "application/json;charset=utf-8",
			data:JSON.stringify(keyVal),
			success:function(data){
				var stockNum = data.STOCK_NUM;
				$('#ffc_addWinForm').find('input[qucln=STOCK_AMOUNT]').val(stockNum); //库存
				$('#ffc_addWinForm').find('input[qucln=STOCK_AMOUNT]').attr('chan','T');
				$('#ffc_addWinForm').find('input[qucln=STOCK_AMOUNT]').next().val(stockNum);
			}
		})
	}
}


//重写删除按钮
function itemRowDelXsff(){
	itemRowDel('ffc');
	sjAmount_cal("ffc_addItemDatagrid")
}

//新书分发弹框绑定根据书名拉取客户信息
function lqclientInfo(){
	//片区经理绑定清除明细数据事件
	$('#ffc_addWinForm').find('input[qucln=O_ID_LASTGR]').unbind('change');
	$('#ffc_addWinForm').find('input[qucln=O_ID_LASTGR]').bind('change',function(){
		oidremove(this);
	}); 
	
	//书名绑定拉取明细事件
	$('#ffc_addWinForm').find('input[qucln=H_ID]').unbind('change');
	$('#ffc_addWinForm').find('input[qucln=H_ID]').bind('change',function(){					// 给行书分发书名列绑定事件
		newkh(this);
	}); 
	
	//新书分发首印数绑定键盘回车事件
	$('#ffc_addWinForm').find('input[qucln=YFF_AMOUNT]').unbind('change');
	$('#ffc_addWinForm').find('input[qucln=YFF_AMOUNT]').bind('keydown',function(event){
			if(event.keyCode=="13"){bindGetsys(this);}
	});
	
	$('#ffc_addWinForm').find('select[qucln=STOCK_ID]').bind('change',function(){					// 给行书分发书名列绑定事件
		getStockAmountSID(this);
	}); 
	
	
}	


//新书分发再次选择片区经理的时候清空书名和明细数据
function oidremove(obj){
	$(obj).attr("chan","T");
	var allRows = $('#ffc_addItemDatagrid').datagrid('getRows');
	if (allRows.length > 0) {
		for ( var i =allRows.length-1; i >=0; i--) {
			$('#ffc_addItemDatagrid').datagrid('deleteRow',i);
		}
	}
	$('#ffc_addWinTable input[qucln=H_ID]').next().val('');
	$('#ffc_addWinTable input[qucln=H_ID]').val('');
}


function bindGetsys(){
	var yffs = $('#ffc_addWinForm input[qucln = YFF_AMOUNT]').val(); //获取首印数的值
	var selRows = $('#ffc_addItemDatagrid').datagrid('getRows');	//获取所有的行
	var ratio = 0;
	if (selRows.length > 0) {
		for ( var i = 0; i < selRows.length; i++) {
			ratio = selRows[i].RATIO;
			selRows[i].PLAN_AMOUNT = (ratio * yffs).toFixed(0);
			$('#ffc_addItemDatagrid').datagrid('beginEdit',i);
			$('#ffc_addItemDatagrid').datagrid('endEdit',i);
		}
	}else{
		$.messager.alert('温馨提示','没有客户的列表！请检查..');
		return;
	}
}


//根据片区经理和商品名称拉取客户
function getkhData(){
	var oIdLastgr =  $('#ffc_addWinForm').find('input[qucln=O_ID_LASTGR]').val(); //获取业务员的值
	var ffcid=$('#ffc_addWinForm').find('input[qucln=FFC_ID]').val();
	var hid= $('#ffc_addWinForm input[qucln = H_ID]').val(); //商品Id
	var dataObj = {};
	$.ajax({
		type:'post',
		url:_m_url+'fxa/getkhData',
		data:{'oIdLastgr':oIdLastgr,"hid":hid,"ffcid":ffcid},
		async : false,
		success:function(data){
			dataObj = data;
		}
	})
	return dataObj;
}

/**
 * 新书分发，书名弹框确认事件方法
 * @return	
 ***/
function newkh(obj){
	$(obj).attr("chan","T");
    var dataObj = getkhData();                //获取拉取数据的数据源
    var dataList = dataObj.dataList;
    var allRows = $('#ffc_addItemDatagrid').datagrid('getRows');
    var clId = '';
    var jhs = 0;
    var address = "";
    var sortNum = getSortNum('ffc');
    var yffs = $('#ffc_addWinForm input[qucln = YFF_AMOUNT]').val(); //首印数
    var dataArray=[];
    var num = parseInt(sortNum)*10+10+parseInt(i)*10;
    var row = $('#ffc_addItemDatagrid').datagrid('getRows');	//获取所有的行 
    if (dataList.length == 0) {
    	if (allRows.length > 0) {
			for ( var i =allRows.length-1; i >=0; i--) {
				$('#ffc_addItemDatagrid').datagrid('deleteRow',i);
			}
		}
    	$.messager.alert('温馨提示','该业务员没有客户信息！');
	}else{
		if (allRows.length > 0) {
			for ( var i =allRows.length-1; i >=0; i--) {
				$('#ffc_addItemDatagrid').datagrid('deleteRow',i);
			}
		}
	    for ( var i = 0; i < dataList.length; i++) {
	        var array={"CC_ID":dataList[i].CC_ID,"O_ID_LASTGR":dataList[i].O_ID_LASTGR}
	        dataArray.push(array);
	        jhs =  parseFloat(dataList[i].RATIO*yffs);    //计划数计算
	        jhs = jhs.toFixed(0);
	        clId = dataList[i].CLIENTS_ID;
	        $('#ffc_addItemDatagrid').datagrid('appendRow', {                    //自动拉取添加新的列
	             CC_ID:dataList[i].CC_ID,                //客户类别
	             O_ID_LASTGR:dataList[i].O_ID_LASTGR,    //业务员
	             C_ID:dataList[i].CLIENTS_ID,            //客户名称
	             RATIO:dataList[i].RATIO,                //客户占比
	             RATIO_YEAR:dataList[i].RATIO_YEAR,        //年份
	             SEND_AMOUNT:"",                             //计划数
	             PLAN_AMOUNT:dataList[i].PLAN_AMOUNT,    //计划数（默认）
	             TM_ITEM_ID:dataList[i].TM_ITEM_ID,    //模板明细外键（隐藏）
	             PLAN_AMOUNT:jhs,                        //计划数
	             C_ADDRESS_SEND:dataList[i].C_ADDRESS_SEND,                //默认收货地址
	             SORT_NUM:parseInt(sortNum)*10+10+parseInt(i)*10, //顺序
	         	 H_PACKAGE_PIECE:dataList[i].H_PACKAGE_PIECE,
	         	 C_DISCOUNT:dataList[i].C_DISCOUNT
	        });
	        comm_xffCal("ffc_addItemDatagrid",(allRows.length-1));
	    }
	    sjAmount_cal("ffc_addItemDatagrid")
	}
}





/***
 * 订单数改变的时候计算
 * @param obj
 * @return
 */
function fx_xfffAmount(obj){
	if($(obj).attr("chan")!="T"){
		return;
	}
	var hid=$('#ffc_addWinForm').find('input[qucln=H_ID]').val();
	var amount=$(obj).val()==""?0:$(obj).val();
	var curDiv=$("div[realdsid][prefix][dsid]");  //获取datagrid的div
	var gridName=$("div[realdsid][prefix][dsid]").attr("id");  //获取datagrid的div
	var currentRow=$(curDiv).datagrid("getEditRow");  //获取正在编辑的行
	var i=$(curDiv).datagrid("getRowIndex",currentRow);
	currentRow["SEND_AMOUNT"]=amount;   //因为数量是可编辑的框，所以此处必须显示赋值，否则 计算通用的明细统计的计算方法中使用的数量有可能是上一次的值
	var packnum = fx_calcuPackNum(hid,amount,currentRow["H_PACKAGE_PIECE"]);
	currentRow["PACKNUM"]=packnum;
	$($(curDiv).datagrid('getCellObj', {"index":i,"colnName":"PACKNUM"})).text(currentRow["PACKNUM"]);   //包册数
	$($(curDiv).datagrid('getCellObj', {"index":i,"colnName":"SEND_AMOUNT"})).text(amount);   //包册数
	sjAmount_cal(gridName);
}


/***
 * 分发计算的计算
 * @return
 */
function comm_xffCal(gridName,index){
	var currentRow=$("#"+gridName).datagrid('getRow',index);
	//获取 定价，数量， 折扣，实洋 ，码洋，包册数
	if(currentRow["SEND_AMOUNT"]!=null&&currentRow["SEND_AMOUNT"]!=""&&currentRow["H_PACKAGE_PIECE"]!=""){
		var packnum = fx_calcuPackNum(currentRow["H_ID"],(currentRow["SEND_AMOUNT"]==null?0:currentRow["SEND_AMOUNT"]),currentRow["H_PACKAGE_PIECE"]);
		currentRow["PACKNUM"]=packnum;
		$($("#"+gridName).datagrid('getCellObj', {"index":index,"colnName":"PACKNUM"})).text(currentRow["PACKNUM"]);   //包册数
	}
}

/****
 * 合计订单数
 * @return
 */
function sjAmount_cal(gridName){
	var allRows = $('#'+gridName).datagrid('getRows');
	var totalSjAmount=0;
	for (var i = 0, len = allRows.length; i < len; i++){
		if(allRows[i]["SEND_AMOUNT"]!=null&&allRows[i]["SEND_AMOUNT"]!=""){
			totalSjAmount = parseInt(totalSjAmount) + Math.abs(allRows[i]["SEND_AMOUNT"]);
		}
	}
	$('#ffc_addWinForm').find('input[qucln=SJ_AMOUNT]').val(totalSjAmount);
	$('#ffc_addWinForm').find('input[qucln=SJ_AMOUNT]').attr('chan','T');
	$('#ffc_addWinForm').find('input[qucln=SJ_AMOUNT]').parent().find("input[so=true]").val(totalSjAmount);
}


